﻿<%@ WebHandler Language="C#" Class="InputCheckItemQrCodeFormHandler" %>

/*Description: 新实测值录入（报工、检验）二维码
'Copyright (c) : 通力凯顿（北京）系统集成有限公司
'Writer: longb 
'create Date:20240301
'Rewriter:
'Rewrite Date:
*/
using System;
using System.Web;
using BusinessRule.DTO;
using System.Web.SessionState;
using DatabaseAccess.DBUtility;
using System.Data.OracleClient;
using System.Data;
using System.Linq;
using Newtonsoft.Json;
using System.Collections.Generic;
using BusinessRule.Business;
using BusinessRule.IBusiness;
using BusinessRule.BusinessFactory;
using System.Configuration;
using System.Text;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using NPOI.SS.UserModel;
using System.Text.RegularExpressions;

public class InputCheckItemQrCodeFormHandler : IHttpHandler, IRequiresSessionState
{

    CurrentUserInfo m_UserInfo;
    uLMSCommonBusiness m_CommonObj = new uLMSCommonBusiness();
    uLMSStepCheckPointIBusiness m_CheckPointObj = uMESBusinessFactory.instance.GetuLMSStepCheckPointObject();
    string usingImg = ConfigurationManager.AppSettings["UsingCheckImageSavePath"];
    public void ProcessRequest(HttpContext context)
    {
        try
        {
            var action = context.Request["action"].ToString();
            var url = context.Request.UrlReferrer.Query.ToString();
            if (url.IndexOf("isVue3") != -1)
            {
                Match match = Regex.Match(url, @"employeename=(.*?)(?:&|$)");
                if (match.Success)
                {
                    string employeename = match.Groups[1].Value;
                    m_UserInfo = m_CommonObj.GetUserInfo(employeename, "");
                }
            }
            else
            {
                m_UserInfo = (CurrentUserInfo)context.Session["CurrentUserInfo"];
            }

            if (m_UserInfo == null)
            {
                context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = false, Message = "数据过期，请重新登录" }));
                return;
            }
            switch (action)
            {
                case "getContainerQRCode"://生成二维码
                    getContainerQRCode(context);
                    break;
                case "importQRCode":
                    importQRCode(context);
                    break;
                case"saveQRCode":
                    saveQRCode(context);
                    break;        
                default:
                    break;
            }
        }
        catch (Exception ex)
        {
            var result = new uMESProcessResult();
            result.Result = false;
            result.Message = ex.Message;
            context.Response.ContentType = "text/html";
            context.Response.Write(JsonConvert.SerializeObject(result));
        }
    }
    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

    private void saveQRCode(HttpContext context) 
    {
        string containerStepWorkReportID = context.Request["containerStepWorkReportID"].ToString();//报工ID
        string type = context.Request["type"].ToString();//1:报工；2：检验

        var selectSQL = @"SELECT c2.MFGWORKFLOWID,w.WORKFLOWSTEPNAME,c2.CONTAINERID,c.CONTAINERID CHILDCONTAINERID,s.SPECNO,st.BUBBLENUMBER,st.STEPCHECKPOINTID,str.stepcheckpointresultid,csw.containerstepworkreportid FROM CONTAINER c 
                     LEFT JOIN CONTAINER c2 ON c2.CONTAINERID =c.PARENTCONTAINERID 
                     LEFT JOIN WORKFLOWSTEP w ON w.WORKFLOWID =c2.MFGWORKFLOWID 
                     left join containerstepworkreport csw on csw.containerid =c.PARENTCONTAINERID and csw.isuse =0 and csw.workflowstepid=w.workflowstepid
                     LEFT JOIN specbase sp ON sp.specbaseid=w.specbaseid
	                 LEFT JOIN spec s ON s.specbaseid=sp.specbaseid OR s.specid=w.specid
	                 LEFT JOIN STEPCHECKPOINT st ON st.WORKFLOWSTEPID =w.WORKFLOWSTEPID
	                 LEFT JOIN STEPCHECKPOINTRESULT str ON str.STEPCHECKPOINTID =st.STEPCHECKPOINTID AND str.CONTAINERID =c2.CONTAINERID AND str.CHILDCONTAINERID =c.CONTAINERID 
                     WHERE c.CONTAINERNAME ='{0}' AND   s.SPECNO='{1}' and st.BUBBLENUMBER='{2}'
                     UNION 
                    SELECT c.MFGWORKFLOWID,w.WORKFLOWSTEPNAME,c.CONTAINERID,'' CHILDCONTAINERID,s.SPECNO,st.BUBBLENUMBER,st.STEPCHECKPOINTID,str.stepcheckpointresultid,csw.containerstepworkreportid FROM CONTAINERCURRENTINFO c 
                     LEFT JOIN WORKFLOWSTEP w ON w.WORKFLOWID =DECODE(c.isinstore,1,c.bsworkflowid,c.workflowid) 
                     left join containerstepworkreport csw on csw.containerid =c.containerid and csw.isuse =0 and csw.workflowstepid =w.workflowstepid
                     LEFT JOIN specbase sp ON sp.specbaseid=w.specbaseid
	                 LEFT JOIN spec s ON s.specbaseid=sp.specbaseid OR s.specid=w.specid
	                 LEFT JOIN STEPCHECKPOINT st ON st.WORKFLOWSTEPID =w.WORKFLOWSTEPID
	                 LEFT JOIN STEPCHECKPOINTRESULT str ON str.STEPCHECKPOINTID =st.STEPCHECKPOINTID AND str.CONTAINERID =c.CONTAINERID 
                     WHERE c.CONTAINERNAME ='{0}' AND   s.SPECNO='{1}' and st.BUBBLENUMBER='{2}'
        ";
        var insertSQL = @"INSERT INTO STEPCHECKPOINTRESULT (lastchangedate,tempdealfail,CHECKERID,CHECKPOINTRESULTNOTE,CHECKPOINTRESULTNOTEDIS,CONTAINERID,CHECKDATE,FACTORYID,STEPCHECKPOINTID,STEPCHECKPOINTRESULTID,containerstepworkreportid,NOTES,CHILDCONTAINERID) 
                                VALUES(sysdate,0,'{0}','{1}','{2}','{3}',sysdate,'{4}','{5}',sys_guid(),'{6}','{7}','{8}')";
        var updateSql = @"UPDATE STEPCHECKPOINTRESULT SET lastchangedate=sysdate,tempdealfail=0,CHECKPOINTRESULTNOTE='{0}',CHECKPOINTRESULTNOTEDIS='{1}',CheckerID='{2}',checkdate=sysdate,ContainerStepWorkReportID='{3}',checkresultdocpath='{4}' where STEPCHECKPOINTRESULTID='{5}'";

        if("1".Equals(type)){//报工实测值录入
            //containerStepWorkReportID = m_UserInfo.EmployeeID;
            insertSQL = @"INSERT INTO STEPCHECKPOINTRESULT (lastchangedate,tempdealfail,WORKERID,WORKCHECKPOINTRESULTNOTE,WORKCHECKPOINTRESULTNOTEDIS,CONTAINERID,CREATEDATE,FACTORYID,STEPCHECKPOINTID,STEPCHECKPOINTRESULTID,containerstepworkreportid,NOTES,CHILDCONTAINERID) 
                                VALUES(sysdate,0,'{0}','{1}','{2}','{3}',sysdate,'{4}','{5}',sys_guid(),'{6}','{7}','{8}')";
            updateSql = @"UPDATE STEPCHECKPOINTRESULT SET lastchangedate=sysdate,tempdealfail=0,WORKCHECKPOINTRESULTNOTE='{0}',WORKCHECKPOINTRESULTNOTEDIS='{1}',WORKERID='{2}',checkdate=sysdate,ContainerStepWorkReportID='{3}',checkresultdocpath='{4}' where STEPCHECKPOINTRESULTID='{5}'";
        }
        
        
       
        var arryList = new System.Collections.ArrayList();
        uMESProcessResult result = new uMESProcessResult();
        DataTable dtt =context.Session["QRDT"]==null?new DataTable(): (DataTable)context.Session["QRDT"];
        foreach(DataRow dr in dtt.Rows)
        {
            try
            {
                string DecBase64 = System.Net.WebUtility.HtmlEncode(dr["QRCode"].ToString());
                string DecJson = DecompressString(DecBase64);
                var Task = JsonConvert.DeserializeObject<MDM_Task>(DecJson);
                var json = JsonConvert.SerializeObject(Task);

                var productName = Task.PN;//零件号
                foreach (MDM_Sample sam in Task.Sps)
                {
                    var childComtainer = sam.BN;//子批次号
                    foreach (MDM_Inspect ins in sam.Ins)
                    {
                        var bubblenumber = ins.BN;//气泡号
                        var meaVal = ins.MeaVal;//实测值
                        var spno = Task.No;//工序号
                        DataTable scrDT = DatabaseHelper.Query_ReturnDatTable(string.Format(selectSQL, productName + "/" + childComtainer, spno, bubblenumber));
                        if (scrDT.Rows.Count==0) { continue; }
                        DataRow drow = scrDT.Rows[0];
                        if (string.IsNullOrWhiteSpace(drow["STEPCHECKPOINTRESULTID"].ToString()))
                        {
                            arryList.Add(string.Format(insertSQL, m_UserInfo.EmployeeID, meaVal, m_CheckPointObj.ConvertTohtml(meaVal, usingImg, false), drow["CONTAINERID"], m_UserInfo.FactoryID, drow["STEPCHECKPOINTID"], drow["containerstepworkreportid"], "二维码导入", drow["CHILDCONTAINERID"]));
                        }
                        else
                        {
                            arryList.Add(string.Format(updateSql, meaVal, m_CheckPointObj.ConvertTohtml(meaVal, usingImg, false), m_UserInfo.EmployeeID, drow["containerstepworkreportid"], "", drow["STEPCHECKPOINTRESULTID"].ToString()));
                        }

                    }
                }
            }catch(Exception ex){
                result.Message = "二维码解析报错：" + ex.Message;
                continue;
            }
        }
        context.Session["QRDT"] = null;
        if (arryList.Count>0)
        {
            result.Result = DatabaseHelper.ExecuteSqlListTran(arryList);
            result.Message = result.Result ? "数据提交成功" : "数据提交失败";
        }
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    
    
    private void importQRCode(HttpContext context) 
    {
        //context.Session["QRDT"] = null;
        uMESProcessResult result = new uMESProcessResult();
        var val = context.Request["val"].ToString();
        if (context.Session["QRDT"] == null)
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("QRCode");
            context.Session["QRDT"] = dt;
        }

        DataTable dtt = (DataTable)context.Session["QRDT"];
        var d = dtt.Select("QRCode='"+val+"'");
        if (d.Length == 0)
        {
            DataRow dr = dtt.NewRow();
            dr["QRCode"] = val;
            dtt.Rows.Add(dr);
        }
        else {
            result.Message="此二维码已扫描过，请勿重复扫码";
        }
        context.Session["QRDT"] = dtt;
        result.PageCount = dtt.Rows.Count.ToString();

        var task = new MDM_Task()
        {
            PN = "YPProduct001",
            No="0010",
            Sps = new List<MDM_Sample>()
            {
                new MDM_Sample(){
                    BN = "2101@re01002",
                    Ins = new List<MDM_Inspect>() { 
                        new MDM_Inspect(){BN="1", SPNO="0010",MeaVal="66"},
                        new MDM_Inspect(){BN="2", SPNO="0010",MeaVal="77"}
                        //new MDM_Inspect(){BN="444", SPNO="0010",MeaVal="88"},
                        //new MDM_Inspect(){BN="555", SPNO="0010",MeaVal="99"}
                    }
                }
            }
        };

       var t= System.Net.WebUtility.HtmlEncode(CompressString(JsonConvert.SerializeObject(task)));
        
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    
    
    private void getContainerQRCode(HttpContext context) 
    {
        var containernames = context.Request["containernames"].ToString();
        var childContainers = context.Request["childContainers"].ToString();
        var checkPoints = context.Request["checkPoints"].ToString();
        uMESProcessResult result = new uMESProcessResult();
        var mDT = getContainerData(containernames,childContainers);
        var realcontainerno = string.Empty;
        if (string.IsNullOrWhiteSpace(childContainers)) 
        {
            foreach(DataRow dr in mDT.Rows)
            {
                realcontainerno +=dr["realcontainerno"].ToString() + ",";
            }
            mDT = mDT.Select("containername='" + mDT.Rows[0]["containername"] + "'").CopyToDataTable();
        }
        
        var InnerHtml = string.Empty;
        var index = 0;
        if (mDT.Rows.Count > 0)
        {
            for (var j = 0; j < mDT.Rows.Count; j++)
            {
                DataRow row = mDT.Rows[j];
                var ddt = getStepCheckPoint(row["containerName"].ToString(),checkPoints);
                if (ddt.Rows.Count > 0)
                {
                    var childContainerNo = string.IsNullOrWhiteSpace(row["childContainerNo"].ToString()) ? realcontainerno.TrimEnd(',') : row["childContainerNo"].ToString();
                    var contentData = getProductJson2(row["productname"].ToString(), childContainerNo, ddt);
                    for (var i = 0; i < contentData.Split(';').Length; i++)
                    {
                        index++;
                        var content = contentData.Split(';')[i].ToString();
                        if (!string.IsNullOrWhiteSpace(contentData))
                        {
                            var ImageUrl = "/InSiteWebApplication/qrcodeimgs/" + CreateQRCodeImg(content, context);//string.Format("data:image/Jpeg;base64,{0}", CreateQRCodeImg(xml));
                            var containerBM = contentData.Split(';').Length > 1 ? "(" + (i + 1) + ")" : "";
                            var Class = ("Imgdiv_" + index) + " " + (j == 0 && i == 0 ? "showImg" : "hiddenImg showImg");
                            InnerHtml += "<div class=' " + Class + "' style=''><p>" + row["containerName"].ToString() + containerBM + "</p>";
                            InnerHtml += "<img  src=" + ImageUrl + " style='height:250px;width:250px;' mode='aspectFit'/></div>";
                        }
                    }
                }
                else
                {
                    result.Message = "查询批次号没有维护检测项信息";
                }
            }
            result.ReturnData = InnerHtml;
            result.PageCount = index.ToString();
        }
        else {
            result.Message = "没有查询到相关批次号信息";
        }
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    private DataTable getContainerData(string containerName, string childContainers)
    {
        var sqlStr = @"SELECT con.containername,con.realcontainerno,con.productname,a.childContainerNo
       FROM containercurrentinfo con 
       LEFT JOIN ( 
       	SELECT wm_concat(SUBSTR(c.CONTAINERNAME,INSTR(c.CONTAINERNAME,'/')+1)) childContainerNo,c.PARENTCONTAINERID 
       	FROM CONTAINER c WHERE c.CONTAINERID IN('{0}') 
       	GROUP by c.PARENTCONTAINERID 
       ) a ON a.PARENTCONTAINERID=con.CONTAINERID 
       WHERE containername in('{1}')";
        return DatabaseHelper.Query_ReturnDatTable(string.Format(sqlStr, childContainers.Replace(",", "','"), containerName.Replace(",", "','")));
    }

    private DataTable getStepCheckPoint(string containerName,string checkpintids)
    {
        var sqlStr = @"SELECT con.containername,con.realcontainerno,con.productname,con.productrevision,con.workflowname,con.workflowrevision,s.specno,
ws.workflowstepid,ws.workflowstepname,st.checkno,
st.bubblenumber,st.floorfloat,st.basevalue,st.ceilfloat,st.singlesign,
s.specno||'$'||st.bubblenumber||'#'||REPLACE(st.floorfloat,'+','')||'|'||st.basevalue||'|'||REPLACE(st.ceilfloat,'-','') sdata
FROM containercurrentinfo con 
LEFT JOIN workflowstep ws ON ws.workflowid=DECODE(con.isinstore,1,con.bsworkflowid,con.workflowid)
LEFT JOIN specbase sp ON sp.specbaseid=ws.specbaseid
LEFT JOIN spec s ON s.specbaseid=sp.specbaseid OR s.specid=ws.specid
LEFT JOIN stepcheckpoint st ON st.workflowstepid=ws.workflowstepid
WHERE st.stepcheckpointid IS NOT NULL AND con.containername IN('{0}')
and st.stepcheckpointid in ('{1}')
ORDER BY s.specno,st.bubblenumber";
        return DatabaseHelper.Query_ReturnDatTable(string.Format(sqlStr, containerName.Replace(",", "','"), checkpintids.Replace(",", "','")));
    }
   
    protected string CreateQRCodeImg(string str,HttpContext context)
    {
        QRCoder.QRCodeGenerator qrGenerator = new QRCoder.QRCodeGenerator();

        QRCoder.QRCodeData qrCodeData = qrGenerator.CreateQrCode(str, QRCoder.QRCodeGenerator.ECCLevel.L);
        QRCoder.QRCode qrcode = new QRCoder.QRCode(qrCodeData);

        Bitmap qrCodeImage = qrcode.GetGraphic(6, Color.Black, Color.White, null, 5, 1, false);
        MemoryStream ms = new MemoryStream();
        //qrCodeImage.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
        var savePath = DateTime.Now.ToString("yyyyMMddHHmmssfff")+".jpg";
        qrCodeImage.Save(context.Server.MapPath("~/qrcodeimgs/"+savePath));//(@"C:\Program Files (x86)\Camstar\InSite Web Application\InSiteWebApplication\qrcodeimgs\123.jpg");
        ms.Close();

        DirectoryInfo directory = new DirectoryInfo(context.Server.MapPath("~/qrcodeimgs/"));
        FileInfo[] files = directory.GetFiles("*.jpg");
        var targetDate = DateTime.Now.AddDays(-1).ToString("yyyyMMdd");
        foreach (var file in files)
        {
            if (file.CreationTime.ToString("yyyyMMdd") == targetDate || file.LastWriteTime.ToString("yyyyMMdd") == targetDate)
            {
                file.Delete();
            }
        }
        
        return savePath;//Convert.ToBase64String(ms.ToArray());
    }

    

    /// <summary>
    /// 零件号，批次号列表，检测项
    /// </summary>
    /// <param name="pn"></param>
    /// <param name="cdt"></param>
    /// <param name="?"></param>
    /// <returns></returns>
    public string getProductJson(string PN,string BN,DataTable checkDT) {
        var pList = new List<MDM_Product>();
        var product = new MDM_Product();
        product.PN = PN;//零件号
        product.BN=BN.Split(',');//批次号列表
        List<MDM_Process> Cts = new List<MDM_Process>();

        List<MDM_TestItem> Its = new List<MDM_TestItem>();
        var index=0;
        var specno=checkDT.Rows[0]["specno"].ToString();
        var content = string.Empty;
        foreach (DataRow dr in checkDT.Rows) 
        {
            if (!specno.Equals(dr["specno"].ToString()))
            {
               
                MDM_Process ct = new MDM_Process();
                ct.Its = Its;
                ct.Qty = Its.Count;
                ct.PN = specno;
                Cts = new List<MDM_Process>();
                Cts.Add(ct);
                specno = dr["specno"].ToString();
                
                //第二道工序--到最后一道工序(第一个检测项)的逻辑
                Its = new List<MDM_TestItem>();
                MDM_TestItem it = new MDM_TestItem();//
                it.BN = dr["bubblenumber"].ToString();//气泡号
                it.UM = dr["singlesign"].ToString();//单向标识
                it.LowVal = dr["ceilfloat"].ToString();//下公差
                it.NomVal = dr["basevalue"].ToString();//理论值
                it.UppVal = dr["floorfloat"].ToString();//上公差
                Its.Add(it);
                if (!isMaxlength(product, Cts))//判断是否超出了最大长度
                {
                    product.Cts = Cts;
                    var ComUrl=System.Net.WebUtility.HtmlEncode(CompressString(JsonConvert.SerializeObject(product)));
                    content += ComUrl + ";";
                    pList.Add(getProduct(ComUrl));
                    Cts = new List<MDM_Process>();
                    product.Cts = Cts;
                }
            }
            else
            {
               
                //第一道工序的所有逻辑、开始第二个往后检测项的逻辑
                MDM_TestItem it = new MDM_TestItem();
                it.BN = dr["bubblenumber"].ToString();//气泡号
                it.UM = dr["singlesign"].ToString();//单向标识
                it.LowVal = dr["ceilfloat"].ToString();//下公差
                it.NomVal = dr["basevalue"].ToString();//理论值
                it.UppVal = dr["floorfloat"].ToString();//上公差
                Its.Add(it);
                
                if (specno.Equals(dr["specno"].ToString())&&Cts.Count==0)
                {
                    MDM_Process ct = new MDM_Process();
                    ct.Its = Its;
                    ct.Qty = Its.Count;
                    ct.PN = specno;
                    Cts = new List<MDM_Process>();
                    Cts.Add(ct);
                }
                
                if (!isMaxlength(product, Cts))
                {
                    product.Cts = Cts;
                    var ComUrl=System.Net.WebUtility.HtmlEncode(CompressString(JsonConvert.SerializeObject(product)));
                    content += ComUrl + ";";
                    pList.Add(getProduct(ComUrl));
                    Cts = new List<MDM_Process>();
                    Its = new List<MDM_TestItem>();
                    product.Cts = Cts;
                }
            }
            index++;
            //最后一道工序，最后一个检测项的逻辑
            if (index == checkDT.Rows.Count)
            {
                MDM_Process ct = new MDM_Process();
                ct.Its = Its;
                ct.Qty = Its.Count;
                ct.PN = specno;
                Cts.Add(ct);
                product.Cts = Cts;
                var ComUrl = System.Net.WebUtility.HtmlEncode(CompressString(JsonConvert.SerializeObject(product)));
                content += ComUrl + ";";
                pList.Add(getProduct(ComUrl));
                Cts = new List<MDM_Process>();
                Its = new List<MDM_TestItem>();
                product.Cts = Cts;
            }
        }

        var JP = JsonConvert.SerializeObject(pList);
        
        for (var j = 0; j < content.TrimEnd(';').Split(';').Length;j++ ) 
        {
            string DecBase64 = System.Net.WebUtility.HtmlEncode(content.Split(';')[j]);
            string DecJson = DecompressString(DecBase64);
        }
        

        var json = Newtonsoft.Json.JsonConvert.SerializeObject(product);

        return content.TrimEnd(';');
    }

    public string getProductJson2(string PN, string BN, DataTable checkDT)
    {
        var pList = new List<MDM_Product>();
        var product = new MDM_Product();
        product.PN = PN;//零件号
        product.BN = BN.Split(',');//批次号列表
        List<MDM_Process> Cts = new List<MDM_Process>();

        List<MDM_TestItem> Its = new List<MDM_TestItem>();
        var index = 0;
        var specno = checkDT.Rows[0]["specno"].ToString();
        var content = string.Empty;
        foreach (DataRow dr in checkDT.Rows)
        {
            if (!specno.Equals(dr["specno"].ToString()))
            {

                MDM_Process ct = new MDM_Process();
                ct.Its = Its;
                ct.Qty = Its.Count;
                ct.PN = specno;
                Cts.Add(ct);
                specno = dr["specno"].ToString();

                //第二道工序--到最后一道工序(第一个检测项)的逻辑
                Its = new List<MDM_TestItem>();
                MDM_TestItem it = new MDM_TestItem();//
                it.BN = dr["bubblenumber"].ToString();//气泡号
                it.UM = dr["singlesign"].ToString();//单向标识
                it.LowVal = dr["ceilfloat"].ToString();//下公差
                it.NomVal = dr["basevalue"].ToString();//理论值
                it.UppVal = dr["floorfloat"].ToString();//上公差
                Its.Add(it);
            }
            else
            {

                //第一道工序的所有逻辑、开始第二个往后检测项的逻辑
                MDM_TestItem it = new MDM_TestItem();
                it.BN = dr["bubblenumber"].ToString();//气泡号
                it.UM = dr["singlesign"].ToString();//单向标识
                it.LowVal = dr["ceilfloat"].ToString();//下公差
                it.NomVal = dr["basevalue"].ToString();//理论值
                it.UppVal = dr["floorfloat"].ToString();//上公差
                Its.Add(it);
            }
            index++;
            //最后一道工序，最后一个检测项的逻辑
            if (index == checkDT.Rows.Count || index%100==0)
            {
                MDM_Process ct = new MDM_Process();
                ct.Its = Its;
                ct.Qty = Its.Count;
                ct.PN = specno;
                Cts.Add(ct);
                product.Cts = Cts;
                var ComUrl = System.Net.WebUtility.HtmlEncode(CompressString(JsonConvert.SerializeObject(product)));
                content += ComUrl + ";";
                pList.Add(getProduct(ComUrl));
                Cts = new List<MDM_Process>();
                Its = new List<MDM_TestItem>();
                product.Cts = Cts;
            }
        }

        var JP = JsonConvert.SerializeObject(pList);

        for (var j = 0; j < content.TrimEnd(';').Split(';').Length; j++)
        {
            string DecBase64 = System.Net.WebUtility.HtmlEncode(content.Split(';')[j]);
            string DecJson = DecompressString(DecBase64);
        }
        var json = Newtonsoft.Json.JsonConvert.SerializeObject(product);
        return content.TrimEnd(';');
    }

    public Boolean isMaxlength(MDM_Product ProductKey, List<MDM_Process> cts)
    {

        ProductKey.Cts = cts;
        string json = JsonConvert.SerializeObject(ProductKey);
        string ComBase64 = CompressString(json);
        string ComUrl =System.Net.WebUtility.HtmlEncode(ComBase64);

        string DecBase64 = System.Net.WebUtility.HtmlEncode(ComUrl);
        string DecJson = DecompressString(DecBase64);
        var GitKey = JsonConvert.DeserializeObject<MDM_Product>(DecJson);
        
        return ComUrl.Length < 200;
    }

    public MDM_Product getProduct(string ComUrl)
    {
        string DecBase64 = System.Net.WebUtility.HtmlEncode(ComUrl);
        string DecJson = DecompressString(DecBase64);
        var GitKey = JsonConvert.DeserializeObject<MDM_Product>(DecJson);
        return GitKey;
    }
    
    public static string CompressString(string text)
    {
        byte[] buffer = Encoding.UTF8.GetBytes(text);

        using (MemoryStream ms = new MemoryStream())
        {
            using (System.IO.Compression.GZipStream gzip = new System.IO.Compression.GZipStream(ms, System.IO.Compression.CompressionMode.Compress, true))
            {
                gzip.Write(buffer, 0, buffer.Length);
            }

            byte[] compressed = ms.ToArray();
            return Convert.ToBase64String(compressed);
        }
    }
    
    public static string DecompressString(string compressedBase64)
    {
        byte[] compressed = Convert.FromBase64String(compressedBase64);

        using (MemoryStream ms = new MemoryStream(compressed))
        {
            using (System.IO.Compression.GZipStream gzip = new System.IO.Compression.GZipStream(ms, System.IO.Compression.CompressionMode.Decompress))
            {
                using (StreamReader reader = new StreamReader(gzip, Encoding.UTF8))
                {
                    return reader.ReadToEnd();
                }
            }
        }
    }
    
 public class MDM_Product
 {
     /// <summary>
     /// 零件号
     /// </summary>
     public string PN { get; set; }

     /// <summary>
     /// 批次号列表
     /// </summary>
     public string[] BN { get; set; }

     /// <summary>
     /// 内容
     /// </summary>
     public List<MDM_Process> Cts { get; set; } 
 }

 /// <summary>
 /// 工序
 /// </summary>
 public class MDM_Process
 {
     /// <summary>
     /// 工序号
     /// </summary>
     public string PN { get; set; }

     /// <summary>
     /// 特征数量 PS:这个工序一共有多少个特征
     /// </summary>
     public int Qty { get; set; }

     /// <summary>
     /// 特征项
     /// </summary>
     public List<MDM_TestItem> Its { get; set; } 
 }

 /// <summary>
 /// 特征项
 /// </summary>
 public class MDM_TestItem
 {
     /// <summary>
     /// 气泡号
     /// </summary>
     public string BN { get; set; }

     /// <summary>
     /// 单向标识
     /// </summary>
     public string UM { get; set; } 

     /// <summary>
     /// 下公差
     /// </summary>
     public string LowVal { get; set; } 

     /// <summary>
     /// 理论值
     /// </summary>
     public string NomVal { get; set; } 

     /// <summary>
     /// 上公差
     /// </summary>
     public string UppVal { get; set; } 
 }
    
    public class MDM_Task
{
    /// <summary>
    /// 零件号
    /// </summary>
    public string PN { get; set; }
    /// <summary>
    /// 工序号
    /// </summary>
    public string No { get; set; }
    public List<MDM_Sample> Sps { get; set; } 
}

public class MDM_Sample
{
    /// <summary>
    /// 样品号
    /// </summary>
    public string BN { get; set; }

    /// <summary>
    /// 测量值
    /// </summary>
    public List<MDM_Inspect> Ins { get; set; } 
}

public class MDM_Inspect
{
    /// <summary>
    /// 气泡号
    /// </summary>
    public string BN { get; set; }
    /// <summary>
    /// 工序号
    /// </summary>
    public string SPNO { get; set; }
    /// <summary>
    /// 测量值
    /// </summary>
    public string MeaVal { get; set; }
}
}
